#include "edragbox.h"

eDragBox::eDragBox(int x, int y, int cr)
 : Fl_Box(x, y, 10, 10) {
  box(FL_THIN_DOWN_BOX);
  corner = cr;
  main_win=this->parent()->parent();
  sahip=(eContainer *)parent();
}

//over-ridden draw method
void eDragBox::draw() {
  int xo = x();
  int yo = y();
  // Draw the button box
  draw_box(box(), color());
  // set the clip region so we only "tile" the box
  fl_push_clip(xo+1, yo+1, w()-3, h()-3);
  // tile the pixmap onto the button face... there must be a better way
  for(int i = 2; i <= w(); i += 6)
    for(int j = 2; j <= h(); j += 6)
    fl_draw_pixmap(grip_tile_xpm, (xo + i), (yo + j));
  fl_pop_clip();
} // draw

// over-ridden handle
int eDragBox::handle(int event) {
  int ret = Fl_Box::handle(event);
  int dx, dy, xr, yr;
  int xg, yg, wg, hg;

  xr = Fl::event_x_root();
  yr = Fl::event_y_root();
  switch (event) {
  case FL_PUSH: // downclick in button stores cursor offsets
    x1 = xr;
    y1 = yr;
    ret = 1;
    break;

  case FL_DRAG: // drag the button (and its parent group) around the screen
    dx = xr - x1; dy = yr - y1;
    x1 = xr; y1 = yr;
    xg = sahip->x();
    yg = sahip->y();
    wg = sahip->w();
    hg = sahip->h();
    //EBoard *board=(EBoard *)main_win->parent();
    Ewindow *ew=(Ewindow *)main_win->parent();
    if(xg+dx>=main_win->x() && yg+dy>=main_win->y()+15 && xg+dx<=main_win->w()+30 && yg+dy<=main_win->h()-80)
    {
      // now resize/move the enclosing group
      // use the middle button to move the window
      if(Fl::event_button2()|| Fl::event_button3()) {
        sahip->position(xg+dx, yg+dy);
        main_win->parent()->redraw();
        main_win->redraw();
      }
      else { // treat as a resize
        if(corner == TL) {
            sahip->resize(xg+dx, yg+dy, wg-dx, hg-dy);
          main_win->parent()->redraw();
          main_win->redraw();
        }
        else if (corner == BR) {
            sahip->resize(xg, yg, wg+dx, hg+dy);
          main_win->parent()->redraw();
          main_win->redraw();
        }
      }
      this->size(w(),h());
      sahip->enboy(sahip->w()-10,sahip->h()-10);
      sahip->pozisyon(sahip->x()+5,sahip->y()+5);
      ew->propertiesTimer(sahip);
    }
    ret = 1;
    break;

  case FL_RELEASE:
    ret = 1;
    break;

  case FL_ENTER:
    fl_cursor(FL_CURSOR_MOVE);
    ret = 1;
    break;

  case FL_LEAVE:
    fl_cursor(FL_CURSOR_DEFAULT);
    ret = 1;
    break;

  default:
    break;
  }
  return ret;
}
